package xyz.jcat.webflux.sucurity;

import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import xyz.jcat.common.util.JsonUtils;

public class ServerUtils {

    public static Mono<Void> writeJson(ServerWebExchange serverWebExchange, Object data) {
        return writeJson(serverWebExchange, HttpStatus.OK, data);
    }

    public static Mono<Void> writeJson(ServerWebExchange serverWebExchange, HttpStatus httpStatus, Object data) {
        ServerHttpResponse response = serverWebExchange.getResponse();
        response.setStatusCode(httpStatus);
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        return response
                .writeWith(Mono.fromSupplier(() -> {
                    DataBufferFactory bufferFactory = response.bufferFactory();
                    return bufferFactory.wrap(JsonUtils.toString(data).getBytes());
                }));
    }
}
